package com.jfinal.web.interceptor;

import com.jfinal.aop.Invocation;
import com.jfinal.core.Const;
import com.jfinal.core.Controller;
import com.jfinal.i18n.I18n;
import com.jfinal.i18n.I18nInterceptor;
import com.jfinal.i18n.Res;
import com.jfinal.kit.StrKit;

import java.util.Locale;

/**
 *
 * @author chen
 * @date 16/8/17
 */
public class MyI18nInterceptor extends I18nInterceptor {

    private static String defaultLocale = Locale.getDefault().getLanguage() + "_" + Locale.getDefault().getCountry();

    @Override
    public void intercept(Invocation inv) {
        Controller c = inv.getController();
        String localeParaName = getLocaleParaName();
        String locale = c.getPara(localeParaName);

        if (StrKit.notBlank(locale)) {
            c.setCookie(localeParaName, locale, Const.DEFAULT_I18N_MAX_AGE_OF_COOKIE);
        } else {
            locale = c.getCookie(localeParaName);
            if (StrKit.isBlank(locale))
                locale = defaultLocale;
        }
        Res res = I18n.use(getBaseName(), locale);
        c.setAttr(getResName(), res);

        inv.invoke();//执行相应的action

    }
}